<?php

declare(strict_types=1);

namespace app\shop\controller\admin\dispatch;

use think\Request;
use think\facade\Db;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use app\shop\model\dispatch\Dispatch as DispatchModel;
use app\shop\model\dispatch\DispatchExpress as DispatchExpressModel;
use app\shop\model\dispatch\DispatchAutosend as DispatchAutosendModel;

/**
 * 配送管理
 */
class Dispatch extends Backend
{
    protected $expressModel;
    protected $autosendModel;
    protected $dispatch_type;

    public function initialize()
    {
        $this->model = new DispatchModel;
        $this->expressModel = new DispatchExpressModel;
        $this->autosendModel = new DispatchAutosendModel;

        $this->dispatch_type = request()->param('type', 'express');
    }


    /**
     * 配送方式列表
     *
     * @return \think\Response
     */
    public function list()
    {
        $dispatchs = $this->model->sheepFilter()->with([$this->dispatch_type])->where('type', $this->dispatch_type)->paginate(request()->param('list_rows', 10));

        return success('获取成功', $dispatchs);
    }




    /**
     * 添加配送方式
     *
     * @return \think\Response
     */
    public function add(Request $request)
    {
        $params = $this->request->only([
            'name', 'type', 'status', 'express', 'autosend'
        ]);
        $this->svalidate($params, ".add");
        $data = $params[$this->dispatch_type] ?? [];
        unset($params['express'], $params['autosend']);

        if ($this->dispatch_type == 'express') {
            // 验证 express
            foreach ($data as $key => $express) {
                $this->svalidate($express, '.express');
            }
        } else if ($this->dispatch_type == 'autosend') {
            // 验证 autosend
            $this->svalidate($data, '.autosend');
        }

        Db::transaction(function () use ($params, $data) {
            unset($params['create_time'], $params['update_time'], $params['id']);      // 删除时间
            $this->model->save($params);

            if ($this->dispatch_type == 'express') {
                foreach ($data as $key => $express) {
                    $express['dispatch_id'] = $this->model->id;
                    $expressModel = new DispatchExpressModel();
                    unset($express['create_time'], $express['update_time'], $express['id']);      // 删除时间
                    $expressModel->save($express);
                }
            } else if ($this->dispatch_type == 'autosend') {
                $data['dispatch_id'] = $this->model->id;
                $autosendModel = new DispatchAutosendModel();
                unset($data['create_time'], $data['update_time'], $data['id']);      // 删除时间
                $autosendModel->save($data);
            }
        });
        return success('保存成功');
    }


    /**
     * 配送方式详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $dispatch = $this->model->with([$this->dispatch_type])->where('type', $this->dispatch_type)->where('id', $id)->findOrFail();

        return success('获取成功', $dispatch);
    }



    /**
     * 修改配送方式
     *
     * @return \think\Response
     */
    public function edit($id)
    {
        $params = $this->request->only([
            'name', 'type', 'status', 'express', 'autosend'
        ]);
        $this->svalidate($params);
        $data = $params[$this->dispatch_type] ?? [];
        unset($params['express'], $params['autosend']);

        if ($this->dispatch_type == 'express') {
            // 验证 express
            foreach ($data as $key => $express) {
                $this->svalidate($express, '.express');
            }
        } else if ($this->dispatch_type == 'autosend') {
            // 验证 autosend
            $this->svalidate($data, '.autosend');
        }
        
        $id = explode(',', $id);
        Db::transaction(function () use ($id, $params, $data) {
            foreach ($this->model->whereIn('id', $id)->cursor() as $dispatch) {
                $dispatch->save($params);

                if ($data) {
                    if ($this->dispatch_type == 'express') {
                        // 修改，不是只更新状态
                        $expressIds = array_column($data, 'id');
                        DispatchExpressModel::where('dispatch_id', $dispatch->id)->whereNotIn('id', $expressIds)->delete();      // 先删除被删除的记录
                        foreach ($data as $key => $express) {
                            if (isset($express['id']) && $express['id']) {
                                $expressModel = $this->expressModel->find($express['id']);
                            } else {
                                $expressModel = new DispatchExpressModel();
                                $express['dispatch_id'] = $dispatch->id;
                            }
                            $express['weigh'] = count($data) - $key;           // 权重
                            unset($express['create_time'], $express['update_time']);
                            $expressModel && $expressModel->save($express);
                        }
                    } else if ($this->dispatch_type == 'autosend') {
                        if (isset($data['id']) && $data['id']) {
                            $autosendModel = $this->autosendModel->find($data['id']);
                        } else {
                            $autosendModel = new DispatchAutosendModel();
                            $data['dispatch_id'] = $dispatch->id;
                        }

                        unset($data['create_time'], $data['update_time']);      // 删除时间
                        $autosendModel && $autosendModel->save($data);
                    }
                }
            }
        });
        return success('更新成功');
    }



    /**
     * 删除配送方式
     *
     * @param string $id 要删除的配送方式列表
     * @return void
     */
    public function delete($id)
    {
        $id = explode(',', $id);

        Db::transaction(function () use ($id) {
            foreach ($this->model->with([$this->dispatch_type])->where('type', $this->dispatch_type)->whereIn('id', $id)->cursor() as $dispatch) {
                if ($this->dispatch_type == 'express') {
                    // 删除相关的 express 数据
                    foreach ($dispatch->express as $express) {
                        $express->delete();
                    }
                } else if ($this->dispatch_type == 'autosend') {
                    // 删除相关的 autosend 数据
                    $dispatch->autosend->delete();
                }

                $dispatch->delete();
            }
        });

        return success('删除成功');
    }


    /**
     * 获取所有配送模板
     *
     * @return \think\Response
     */
    public function select()
    {
        $dispatchs = $this->model->sheepFilter()->field('id, name, type, status')->normal()->where('type', $this->dispatch_type)->select();

        return success('获取成功', $dispatchs);
    }
}
